const shell = require("shelljs")
const path = require('path')
const os = require('os')

const logs = require('./log')
const { get, hasFile, sleep } = require('./common')

let sleepTime = 0

let WECHAT_CLI_PATH
let sysType = os.type()

if (sysType === 'Windows_NT') {
    WECHAT_CLI_PATH = 'cli'
} else {
    WECHAT_CLI_PATH = './cli'
}

logs.log('微信环境', sysType, WECHAT_CLI_PATH)
logs.log('支付宝环境', sysType, 'minidev')


function getPlatformInfo (platform, config, basePath, env) {
    const ideDir = get(config, `${platform}.ideDir`)
    const execCodeType = env === 'development' ? 'dev' : 'build'
    const projectDir = path.resolve(basePath, `./dist/${execCodeType}/${platform}`)
    return {
        ideDir,
        execCodeType,
        projectDir
    }
}

function openReady ({ ideDir, projectDir, flagFile, remove } = {}) {
    cancelOpen()

    if (remove) {
        // 如果是在编译之前打开编译器，删除project.config.json，监听该文件，如果存在则说明已经编译完成
        shell.rm('-f', path.resolve(projectDir, `./${flagFile}`))
    }

    async function hasOpenReally (resolve) {
        const isHasConfigJson = await hasFile(`./${flagFile}`, projectDir)

        if (isHasConfigJson) {
            await sleep(200)
            resolve(true)
        } else {
            await sleep(4000)
            hasOpenReally(resolve)
        }
    }

    return new Promise(async resolve => {
        if (ideDir) {
            await sleep(2000)
            logs.wait('等待项目编译完成，请稍后...')
            hasOpenReally(resolve)
        } else {
            if (!ideDir) {
                logs.warning('当前调试器路径为空, 自动打开调试器功能将失效')
            }
            resolve(false)
        }
    })
}

function cancelOpen () {
    clearTimeout(sleepTime)
}

function compileBefore ({ config, NODE_ENV, UNI_PLATFORM, PRESET_PATH }) {
    if (config && config.compileBefore) {
        try {
            config.compileBefore({ config, NODE_ENV, UNI_PLATFORM, PRESET_PATH })
        } catch (e) {
            //
        }
    }
}

function compiled ({ config, NODE_ENV, UNI_PLATFORM, PRESET_PATH }) {
    if (config && config.compiled) {
        try {
            config.compiled({ config, NODE_ENV, UNI_PLATFORM, PRESET_PATH })
        } catch (e) {
            //
        }
    }
}

module.exports = {
    logs,
    WECHAT_CLI_PATH,
    getPlatformInfo,
    openReady,
    compileBefore,
    compiled,
    cancelOpen
}
